'use strict';

/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "Util" }] */
const host = window.location.host;
const isLocal = (function () {
    return !host || host.indexOf('localhost') === 0 || ['192', '168', '10', '76'].indexOf(host.split('.').shift()) > -1;
}());
const isStaging = (function () {
    return host.indexOf('stage') >= 0 || host.indexOf('test') >= 0 || host.indexOf('dev') >= 0;
}());


const Util = {
    isLocal: isLocal,
    isOnline: isLocal && isStaging,
    isTest: isStaging || isLocal,
    userInfo: {},
    /**
     * Request 支持post和get请求，默认不传method是get
     * params结构
     * {
     *   url: '', 必须参数
     *   method: '', // 非必须参数  默认get
     *   data: '', //get的data, 非必须参数  默认 {}
     *   formData: '', //post的data post下默认{}
     *   success (){} 成功回调 必须参数
     *   error (){} 失败回调 必须参数
     * }
     */
    Request(params) {
        let xhr = new XMLHttpRequest();
        let url = this.appendQuery(params.url, params.data || {});
        let method = params.method || 'GET';
        let sendData = null;
        xhr.open(method, url, true);
        xhr.timeout = 8000;
        if (method.toUpperCase() === 'POST') {
            // 用POST的时候一定要有这句
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            sendData = params.formData || {};
        }
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200 || xhr.status === 304) {
                    let parseJson = JSON.parse(xhr.response.replace(/(^\*\*YGKJ)|(YGKJ##$)/g, ''));
                    let json = parseJson.jsonr || parseJson;
                    if (json.status === '00') {
                        params.success(json.data);
                    } else {
                        params.error(json.status);
                    }
                } else {
                    params.error(xhr.response);
                }
            }
        };
        xhr.ontimeout = () => {
            // XMLHttpRequest timed out.
            params.error('timeout');
        };
        xhr.send(sendData);
    },
    getCookie(cookieName) { // cookie
        let strCookie = document.cookie;
        let arrCookie = strCookie.split("; ");
        for (let i = 0; i < arrCookie.length; i++) {
            let arr = arrCookie[i].split("=");
            if (cookieName == arr[0]) {
                return arr[1];
            }
        }
        return "";
    },
    setCookieValue(_Name, _Value, _Expires, _Type) {
        let _LargeExpDate = new Date()
        if (typeof _Expires === 'number' && !isNaN(_Expires)) {
            if (_Expires !== 0) {
                if (typeof _Type === 'number' && !isNaN(_Type) && _Type) {
                    _LargeExpDate.setTime(_LargeExpDate.getTime() + (_Expires * 1000))
                } else {
                    _LargeExpDate.setTime(_LargeExpDate.getTime() + (_Expires * 24 * 3600 * 1000))
                }
            } else {
                _LargeExpDate = null
            }
        } else {
            _LargeExpDate.setTime(_LargeExpDate.getTime() + (365 * 24 * 3600 * 1000))
        }
        document.cookie = _Name + '=' + escape(_Value) + (_LargeExpDate != null ? ';expires=' + _LargeExpDate.toGMTString() : '') + ';path=/'
    },
    getQueryString(name) { // url参数  Util.getQueryString('id')
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
    scrolltop(e) { // 返回顶部   Util.scrolltop(event)
        e.preventDefault();
        window.scrollTo({
            top: 0,
            behavior: "smooth"
        });
        // $('html,body').animate({"scroll-top": "0px"}, 500, "linear");
    },
    scrollEle(ele) {   // 定位到某个元素 Util.scrollEle(idName)
        window.scrollTo({
            top: document.getElementById(ele).offsetTop,
            behavior: "smooth"
        });
        // let top = $(ele).offset().top;
        // $('html,body').animate({"scroll-top": top - 64 + "px"}, 500, "linear");
    },
    setPageTitle(title) { //设置页面标题
        document.title = title
    },
    isWeixin() {
        let isWx = window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i)
        if (!isWx) {
            return false
        } else {
            return isWx[0] === 'micromessenger'
        }
    },
    wxOauth() {
        let wxUid = this.getCookieValue('wx_nd_wxuid')
        let unionid = this.getCookieValue('unionid')
        let unionidSalt = this.getCookieValue('unionidSalt')
        let _url = encodeURIComponent(location.href)
        let wxGrantStatus = this.getCookieValue('wx_nd_grant_status')
        if (!wxUid) {
            location.href = '//m.mp.oeeee.com/user.php?m=WXOAuth2&a=baseScope&url2go=' + _url
        }
        if (!unionid || !unionidSalt) {
            location.href = '//m.mp.oeeee.com/user.php?m=WXOAuth2&a=infoScope&regchannel=wechat_cmtpost&url2go=' + _url + encodeURIComponent('&wxNdGrant=1')
        }
    },
    loadScript(url, callback) {
        let head = document.getElementsByTagName('head')[0]
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = url
        script.onload = script.onreadystatechange = () => {
            if ((!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) {
                callback && callback()
                // Handle memory leak in IE
                script.onload = script.onreadystatechange = null
                if (head && script.parentNode) {
                    head.removeChild(script)
                }
            }
        }
        head.insertBefore(script, head.firstChild)
    },
    wxShare(options) {
        if (!this.isWeixin()) {
            return
        }
        this.loadScript('//m.chinajsb.cn/server.php?s=/WxHelper/config&domain=m.chinajsb.cn', () => {
            let title = options.title
            let summary = options.summary
            let thumb = options.thumb
            let link = options.link
            wx.config({
                debug: false,
                appId: oe_wxconfig.appId,
                timestamp: oe_wxconfig.timestamp,
                nonceStr: oe_wxconfig.nonceStr,
                signature: oe_wxconfig.signature,
                jsApiList: [
                    'onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareQZone', 'onMenuShareWeibo'
                ]
            })
            wx.ready(() => {
                wx.onMenuShareAppMessage({
                    title: title,
                    desc: summary,
                    link: link,
                    imgUrl: thumb,
                    success: function () {
                    },
                    cancel: function () {
                    }
                })
                wx.onMenuShareTimeline({
                    title: title,
                    desc: summary,
                    link: link,
                    imgUrl: thumb,
                    success: function () {
                    },
                    cancel: function () {
                    }
                })
                wx.onMenuShareQQ({
                    title: title,
                    desc: summary,
                    link: link,
                    imgUrl: thumb,
                    success: () => {
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: () => {
                        // 用户取消分享后执行的回调函数
                    }
                })
                wx.onMenuShareQZone({
                    title: title,
                    desc: summary,
                    link: link,
                    imgUrl: thumb,
                    success: () => {
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: () => {
                        // 用户取消分享后执行的回调函数
                    }
                })
                wx.onMenuShareWeibo({
                    title: title,
                    desc: summary,
                    link: link,
                    imgUrl: thumb,
                    success: () => {
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: () => {
                        // 用户取消分享后执行的回调函数
                    }
                })
            })
        })
    }
};


// 弹框组件
// * FunL: 表示左侧按钮的触发事件
// * FunR: 代表右侧的触发事件
// * 默认事件 关闭弹出层

let PARAMS;
let DEFAULTPARAMS = {Title: "标题", Content: "", BtnL: "确定", BtnR: "取消", FunL: new Object, FunR: new Object};

Util.DialogByZ = {
    //弹出提示框
    Alert(params) {
        Util.Show(params, "Alert");
        // Util.DialogByZ.Alert({Title: "提示", Content: "隔壁的狗总往你的花园里撒尿",BtnL:"我知道了",FunL:aaa})
    },
    //弹出确认框
    Confirm(params) {
        Util.Show(params, "Confirm");
    },
    // Util.DialogByZ.Confirm({Title: "", Content: "你是世界上最美的</br>毋庸置疑",FunL:confirmL,FunR:Immediate})
    //自动显示弹框
    Autofade(params) {
        Util.Show(params, "Autofade")
    },
    // Util.DialogByZ.Autofade({Content: "据说牛皮糖是拿皮鞋做的！"})
    //加载图形
    Loading(Url) {
        Util.loadBox(Url)
        // Util.DialogByZ.Loading('images/loading.png')
    },
    //关闭弹出框
    Close() {
        if (document.getElementsByClassName('zbox-popup')[0]) {
            document.body.removeChild(document.getElementsByClassName('zbox-popup')[0])
        }
        if (document.getElementsByClassName('zbox-popup-backdrop')[0]) {
            document.body.removeChild(document.getElementsByClassName('zbox-popup-backdrop')[0])
        }

    }
}

//初始化参数
Util.Init = (params) => {
    if (params != undefined && params != null) {
        PARAMS = Object.assign({}, DEFAULTPARAMS, params)
    }
};
Util.loadBox = (Url) => {
    let url = Url;
    let dislogContainer = `<div class="zbox-popup" style="display: block;"><img id="zchange" src="${url}"></div>`
    setTimeout(() => {
        if (document.getElementsByClassName('zbox-popup')[0]) {
            document.getElementsByClassName('zbox-popup')[0].classList.add('zbox-popup-in')
        }
        if (document.getElementsByClassName('zbox-popup-backdrop')[0]) {
            document.getElementsByClassName('zbox-popup-backdrop')[0].classList.add('zbox-active')
        }
    }, 30)
    document.body.insertAdjacentHTML('beforeEnd', dislogContainer);
}
Util.Show = (params, caller) => {
    Util.Init(params);
    var dislogContainer;
    var dialogInner;
    var dialogBtn;
    var blackFilter = '<div class="zbox-popup-backdrop" style="display: block;"></div>';
    if (caller === 'Autofade') {
        dislogContainer = `<div class="zbox-toast-container"><div class="zbox-toast-message">${PARAMS.Content}</div></div>`;
        document.body.insertAdjacentHTML('beforeEnd', dislogContainer);
        setTimeout(() => {
            document.getElementsByClassName('zbox-toast-container')[0].classList.add('zbox-active')
        }, 30)
        setTimeout(() => {
            document.body.removeChild(document.getElementsByClassName('zbox-toast-container')[0])
        }, 3000)
    } else {
        dislogContainer = document.createElement('div')
        dislogContainer.className = 'zbox-popup'
        dislogContainer.style.display = 'block'
        dialogInner = `<div class="zbox-popup-inner"><div class="zbox-popup-title">${PARAMS.Title}</div><div class="zbox-popup-text">${PARAMS.Content}</div></div>`;
        if (caller === 'Confirm') {
            dialogBtn = `<div class="zbox-popup-buttons"><span class="zbox-popup-button" index="0">${PARAMS.BtnL}</span><span class="zbox-popup-button R" index="1">${PARAMS.BtnR}</span></div>`;
        } else {
            dialogBtn = `<div class="zbox-popup-buttons"><span class="zbox-popup-button" index="0">${PARAMS.BtnL}</span></div>`;
        }
        dislogContainer.innerHTML = dialogInner + dialogBtn
        setTimeout(() => {
            if (document.getElementsByClassName('zbox-popup')[0]) {
                document.getElementsByClassName('zbox-popup')[0].classList.add('zbox-popup-in')
            }
            if (document.getElementsByClassName('zbox-popup-backdrop')[0]) {
                document.getElementsByClassName('zbox-popup-backdrop')[0].classList.add('zbox-active')
            }
        }, 10)
        document.body.insertAdjacentHTML('beforeEnd', blackFilter);
        document.body.appendChild(dislogContainer)

        let oZbox_popup_button = document.getElementsByClassName('zbox-popup-button')
        for (let i of oZbox_popup_button) {
            i.onclick = () => {
                let indexs = i.getAttribute('index')
                if (Number(indexs) === 0) {
                    //左侧按钮
                    if (typeof PARAMS.FunL === "function") {
                        PARAMS.FunL();
                    } else {
                        Util.DialogByZ.Close();
                    }
                } else {
                    //右侧按钮
                    if (typeof PARAMS.FunR === "function") {
                        PARAMS.FunR();
                    } else {
                        Util.DialogByZ.Close();
                    }
                }
                return false;
            }
        }
    }
}

const $ = {}

$.id = (ele) => {
    return document.getElementById(ele)
}





